package top.huxy.boot.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.huxy.boot.config.RedisKeyConfig;
import top.huxy.boot.service.MailService;
import top.huxy.boot.util.ExceptionUtils;
import top.huxy.boot.util.NamedThreadFactory;
import top.huxy.boot.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author HuXY
 * @Classname MailServiceImpl
 * @Description MailServiceImpl
 * @Date 2021/9/5 10:22
 * @Created by huxy
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    @SuppressWarnings("all")
    private JavaMailSender mailSender;

    @Resource
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    ExecutorService pool = new ThreadPoolExecutor(1, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("MailServiceImpl-sendMail"));

    @Override
    public String sendEmailYzmMail(String userEmailAddress) {
        MimeMessage message = mailSender.createMimeMessage();
        Context context = new Context();
        String yzm = StringUtils.getRandomNumberString(4);
        context.setVariable("yzm", yzm);
        String emailContent = templateEngine.process("EmailYzm", context);
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(userEmailAddress);
            helper.setSubject("登录验证码");
            helper.setText(emailContent, true);
            helper.setFrom(from);
        } catch (MessagingException e) {
            log.error("邮件发送失败", e);
            return null;
        }

        pool.submit(() -> {
            try {
                log.info("给邮箱发送验证码邮件,to={},yzm={}",userEmailAddress, yzm);
                long startTime = System.currentTimeMillis();
                mailSender.send(message);
                long endTime = System.currentTimeMillis();
                log.info("验证码邮件发送成功,to={},yzm={},time={}", userEmailAddress, yzm, (endTime - startTime));
            } catch (Exception e) {
                log.error("发送邮件失败", e);
                ExceptionUtils.logError(e);
            }
        });

        //验证码有效期30分钟
        String redisKey = RedisKeyConfig.EMAIL_YZM_PREFIX + userEmailAddress;

        //保存验证码
        redisTemplate.opsForValue().set(redisKey, yzm);
        redisTemplate.expire(redisKey, 30L, TimeUnit.MINUTES);
        return yzm;
    }
}
